import json
import sys


def del_pos(s):
    """
    Deletes part-of-speech encoding from an entity string, if present.
    :param s: Entity string.
    :return: Entity string with part-of-speech encoding removed.
    """
    if s.endswith("/n") or s.endswith("/a") or s.endswith("/v") or s.endswith("/r"):
        s = s[:-2]
    return s


def parse(line):
    ls = line.split('\t')
    if ls[2].startswith('/c/en/') and ls[3].startswith('/c/en/'):
        relation = ls[1].split("/")[-1].lower()
        head = del_pos(ls[2]).split("/")[-1].lower()
        tail = del_pos(ls[3]).split("/")[-1].lower()
    else:
        return None

    if not head.replace("_", "").replace("-", "").isalpha():
        return None

    if not tail.replace("_", "").replace("-", "").isalpha():
        return None

    if relation.startswith("*"):
        relation = relation[1:]
        tmp = head
        head = tail
        tail = tmp

    data = json.loads(ls[4])

    line = relation + "," + head + "," + tail + "," + str(data["weight"]) + "\n"

    return line


def extract(path):

    index = 0

    with open(path, encoding="utf-8") as f, open("output.csv","w", encoding="utf-8") as of:
        line = f.readline()
        while line != "":
            line = parse(line)
            if line is not None:
                index = index + 1
                print("Extracting: ", index, ": ", line)
                of.write(line)

            line = f.readline()

    print("Extracting Finished!")


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("ConceptNet csv path required.")
    else:
        extract(sys.argv[1])
